package com.tonann.app.conf;

import com.tonann.app.domain.AppDevice;
import com.tonann.app.service.IAppDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IAppDeviceService deviceService;

    private final String KEY_PRE = "device:deviceId:isOnline:";

    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);

    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key,可以做自己的业务
        String expiredKey = message.toString();
        System.out.println(expiredKey);
        if (expiredKey.contains(KEY_PRE)){
            String id = expiredKey.replace(KEY_PRE,"");
            try{
                Long deviceId = Long.parseLong(id);
                AppDevice device = deviceService.selectAppDeviceByDeviceId(deviceId);
                if (device != null){
                    device.setIsOnline("0");
                    deviceService.updateAppDeviceStatus(device);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}